package com.darrenchan.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2019-12-18 22:38
 */
public class Q3 {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int max = 0;
        int j = 0;
        Set<Character> res = new HashSet<>();

        for (int i = 0; i < s.length(); i++) {
            while (j < s.length() && !res.contains(s.charAt(j))) {
                res.add(s.charAt(j));
                max = Math.max(max, j - i + 1);
                j++;
            }
            res.remove(s.charAt(i));
        }

        return max;
    }

    public int lengthOfLongestSubstring2(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int j = 0;
        int max = 0;
        int[] res = new int[256];
        for (int i = 0; i < s.length(); i++) {
            while (j < s.length() && res[s.charAt(j)] == 0) {
                res[s.charAt(j)]++;
                max = Math.max(max, j - i + 1);
                j++;
            }
            res[s.charAt(i)]--;
        }
        return max;
    }

    public int lengthOfLongestSubstring3(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int i = 0;
        int max = 0;
        int[] res = new int[256];
        for (int j = 0; j < s.length(); j++) {
            res[s.charAt(j)]++;
            while(res[s.charAt(j)] > 1) {
                res[s.charAt(i)]--;
                i++;
            }
            max = Math.max(max, j - i + 1);
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(new Q3().lengthOfLongestSubstring("abcabcbb"));
    }
}
